/**
 * ...
 * @author Krzysztof Rozalski
 */

package hapi.db;

#if php
import php.db.Manager;
import php.db.Object;
#elseif neko
import neko.db.Manager;
import neko.db.Object;
#end

class RecordManager<T:Object> extends Manager<T> {
	
	private static var GLOBAL_LOCK_RECORDS = false;
	private static var GLOBAL_MANAGER_INDEX = 0;
	
	var cache_key_prefix:String;
	
	public function new(cls, ?tableName:String = null) {
		super(cls);
		if ( tableName != null) this.table_name = tableName;
		cache_key_prefix = (GLOBAL_MANAGER_INDEX++) +"_";
	}
	
	public function toString() {
		return Type.getClassName(Type.getClass(this)) + "(" + this.dbClass() + " -> " + this.table_name + ")";
	}
	
	public override function all( ?lock : Bool ) {
		if (lock == null) lock = GLOBAL_LOCK_RECORDS;
		return super.all(lock);
	}
	
	public override function get( id : Int, ?lock : Bool ) : T { 
		if (lock == null) lock = GLOBAL_LOCK_RECORDS;
		return super.get(id, lock);
	}
	
	public override function getWithKeys( keys : { }, ?lock : Bool ) : T { 
		if (lock == null) lock = GLOBAL_LOCK_RECORDS;
		return super.getWithKeys(keys, lock);
	}
	
	public override function object( sql : String, lock : Bool ) : T {
		if (lock == null) lock = GLOBAL_LOCK_RECORDS;
		return super.object(sql, lock);
	}
	
	public override function objects( sql : String, lock : Bool ) : List < T > { 
		if (lock == null) lock = GLOBAL_LOCK_RECORDS;
		return super.objects(sql, lock);
	}
	
	public override function search( x : { }, ?lock : Bool ) : List < T > {
		if (lock == null) lock = GLOBAL_LOCK_RECORDS;
		return super.search(x, lock);
	}
	
	public static function setGlobalLock(lock:Bool) {
		GLOBAL_LOCK_RECORDS = lock;
	}
	
	override function makeCacheKey( x : T ) : String {
		return cache_key_prefix + super.makeCacheKey( x );
	}
}
